// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;
declare const wx: any;
@ccclass
export default class NewItem extends cc.Component {


  updateItem(index: number, data: any) {
    let name = this.node.getChildByName("name")
    name.getComponent(cc.Label).string = data.nickname;

    let score = this.node.getChildByName("score")
    score.getComponent(cc.Label).string = data.KVDataList[0].value;

    this.createImage(this.node.getChildByName('mask').getChildByName("Sprite02").getComponent(cc.Sprite), data.avatarUrl);

    if (index === 0 || index === 1 || index === 2) {
      const url = 'bg/ic_' + (index + 1);
      const _this = this;
      cc.loader.loadRes(url, cc.SpriteFrame, function (err, spriteFrame) {
        _this.node.getChildByName("Sprite01").getComponent(cc.Sprite).spriteFrame = spriteFrame;
      });

      this.node.getChildByName("Sprite01").active = true;
      this.node.getChildByName("number").active = false;

    } else {
      this.node.getChildByName("Sprite01").active = false;
      this.node.getChildByName("number").active = true;

      this.node.getChildByName("number").getComponent(cc.Label).string = index + 1 + '';
    }
  }

  private createImage(sprite, url) {
    let image = wx.createImage();
    image.onload = function () {
      let texture = new cc.Texture2D();
      texture.initWithElement(image);
      texture.handleLoadedTexture();
      sprite.spriteFrame = new cc.SpriteFrame(texture);
      sprite.node.width = 60;
      sprite.node.height = 60;
    };
    image.src = url;
  }
}
